package org.dragonnova.business.modules.sys.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dragonnova.business.dao.UsersDao;
import org.dragonnova.business.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

@Service("userService")
@Transactional
public class UserServiceImpl {
	@Autowired
	private UsersDao userDao;

	public List<User> userCount() throws Exception {
		return userDao.getAllUser();
	}

	public Map<String, Object> findUser(Map<String, Object> map) throws Exception {
		return userDao.findUser(map);
	}

	public User addUser(User user) throws Exception {
		return (User) userDao.saveOrUpdateObj(user);
	}

	/**
	 * 修改密码
	 * 
	 * @param id
	 * @param oldPwd
	 * @param newPwd
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> updatePassword(Integer id, String oldPwd, String newPwd) throws Exception {
		User user = (User) userDao.findById(User.class, id);
		Map<String, Object> map = new HashMap<>();
		if (DigestUtils.md5DigestAsHex(oldPwd.getBytes()).equals(user.getPassword())) {
			int result = userDao.updatePassword(id, DigestUtils.md5DigestAsHex(newPwd.getBytes()));
			if (result > 0) {
				map.put("message", "修改成功");
				map.put("result", "0");
			} else {
				map.put("message", "修改失败");
				map.put("result", "-1");
			}
		} else {
			map.put("message", "原密码错误");
			map.put("result", "-1");
		}
		return map;
	}

	public Map<String, Object> delUser(Integer id)  throws Exception {
		userDao.delById(User.class,id);
		Map<String, Object> map = new HashMap<>();
		map.put("message", "删除成功！");
		map.put("result", "0");
		return map;
	}

}
